//
//  HRUserGoodsListViewController.m
//  haierapp
//
//  Created by Xia Zhiyong on 14-8-12.
//  Copyright (c) 2014年 haier. All rights reserved.
//

#import "HRUserGoodsListViewController.h"

#import "HRUserOrderDetailViewController.h"

#import "HRGoodsInfoViewController.h"

#import "HROrderList.h"

#import "HROrderProgressViewController.h"
#import "HROrderApplyViewController.h"

#import "HRCancelOrderView.h"
#import "HRPaymentManager.h"

#import "HRPaysucceedViewController.h"
#import "HREvaluationViewController.h"

#define HEIGHT_HEADER_CELL 40.0f

#define HEIGHT_CELL 80.0f

@interface HRUserGoodsListViewController (){
    NSMutableArray *_orderArray;
    
    HUDTYPE _curHudType;//提示页面类型
    
    NSMutableArray *_filterState;//订单状态
    
}

@end

@implementation HRUserGoodsListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorFromHexRGB:@"f0f0f0"];
    if (__CUR_IOS_VERSION >= __IPHONE_7_0)
    {
        self.edgesForExtendedLayout= UIRectEdgeNone;
    }
    
    self.tableView.backgroundColor=[UIColor clearColor];
    //去除多余的间隔线
    UIView *footerView=[[UIView alloc] init];
    footerView.backgroundColor=[UIColor clearColor];
    [self.tableView setTableFooterView:footerView];
    
    NSString *titleName=@"";
    _filterState=[[NSMutableArray alloc]init];
    _orderArray=[[NSMutableArray alloc]init];
    
    switch (_orderListType) {
        case ORDERLIST_TYPE_WAIT_COMMENT:
            titleName=@"待评价";
            [_filterState addObjectsFromArray:@[@"已收货",@"已签收",@"交易成功"]];
            _curHudType=HUDTYPE_ORDER_WAIT_COMMENT;
            break;
        case ORDERLIST_TYPE_WAIT_SEND:
            titleName=@"待发货";
            [_filterState addObjectsFromArray:@[@"已支付"]];
            _curHudType=HUDTYPE_ORDER_WAIT_SEND;
            break;
        case ORDERLIST_TYPE_RETURNING:
            titleName=@"退款中";
            #warning 退款功能暂时没做
            [_filterState addObject:@"退款中"];
            _curHudType=HUDTYPE_ORDER_RETURN;
            break;
        case ORDERLIST_TYPE_WAIT_RECEIVE:
            _curHudType=HUDTYPE_ORDER_WAIT_RECEIVE;
            [_filterState addObjectsFromArray:@[@"已发货"]];
            titleName=@"待收货";
            break;
        case ORDERLIST_TYPE_RECEIVED:
            _curHudType=HUDTYPE_ORDER_WAIT_RECEIVE;
            [_filterState addObjectsFromArray:@[@"已签收",@"已收货"]];
            titleName = @"已收货";
            break;
        case ORDERLIST_TYPE_WAIT_PAYMENT:
            titleName=@"待付款";
            [_filterState addObjectsFromArray:@[@"未支付",@"已付定金"]];
            _curHudType=HUDTYPE_ORDER_WAIT_PAYMENT;
            break;
        default:
            titleName=@"所有订单";
            _curHudType=HUDTYPE_ORDER_ALL;
            
            //导航栏添加搜索按钮
//            NavigationViewController *navigationController=(NavigationViewController *)self.navigationController;
//            [navigationController showOrderSearchIcon:self withSearchAction:@selector(searchOrderAction)];
            
            break;
    }
    self.navigationItem.title = titleName;
   
}

-(void)viewWillAppear:(BOOL)animated{
    
    [self loadOrderData];
    
    [super viewWillAppear:animated];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - methods

-(void)loadOrderData{
    //加载订单数据
    BOOL hasNewOrder=[HRCommonData shareCommonData].hasNewOrder;
    
    if (hasNewOrder) {
        //从远程加载数据
        [self loadOrderListFromServer];
    }else{
        //从缓存中加载数据
        [self loadOrderFromCache];
    }
}

//从服务器获取订单列表
-(void)loadOrderListFromServer{
    
    [self showCustomLoadingHud:kLoading inView:nil];
    
    [HRInterfaceManager getOrderListWithCompletion:^(BOOL isSucceed, NSString *message, id data) {
        
        [self hideCustomLoadingHud];
        
        if (isSucceed) {
            [HRCommonData shareCommonData].orderList=(HROrderList *)data;//全局暂存
            
            //订单数据已经是最新
            [HRCommonData shareCommonData].hasNewOrder=NO;
        }else if([message isEqualToString:NO_WIFI_ERROR_CODE]){
            //没有网络
            [self showHudByType:HUDTYPE_NO_WIFI];
            return;
            
        }else{
            [HRCommonData shareCommonData].orderList=nil;
            [self showTextHUD:message];
        }
        
        //从缓存加载数据
        [self loadOrderFromCache];
    }];
}

//从缓存中获取指定类型的订单列表
-(void)loadOrderFromCache{
    
    [_orderArray removeAllObjects];
    
    HROrderList *orderList=[HRCommonData shareCommonData].orderList;
    
    if ([_filterState count]==0) {
        _orderArray=[NSMutableArray arrayWithArray:orderList.list];
    }else{
        for (HROrder *order in orderList.list) {
            for (NSString *status in _filterState) {
                if ([order.orderStateStr isEqualToString:status]) {
                    
                    //未评价需要指定条件
                    if (_orderListType==ORDERLIST_TYPE_WAIT_COMMENT) {
                        for (HROrderProductInfo *product in order.productList) {
                            if ([product.isEvaluate isEqualToString:@"否"]) {
                                //有未评价的商品，添加该订单
                                [_orderArray addObject:order];
                                break;
                            }
                        }
                    }else{
                        //订单符合条件
                        [_orderArray addObject:order];
                    }
                    
                }
            }
        }
    }
    
    //隐藏为空的页面提示
    [self hideHud];
    
    if ([_orderArray count]>0) {
        //重新加载表数据
        [self.tableView reloadData];
    }else{
        //显示页面为空提示
        [self showHudByType:_curHudType];
    }
    
    
    //页面加载耗时
    [self analysisEnd:nil];
}

//根据状态的文字判断状态
-(ORDER_TYPE)getOrderTypeByTextStatus:(NSString *)statusText{

    ORDER_TYPE type;
    
    if ([statusText isEqualToString:@"未支付"] || [statusText isEqualToString:@"已付定金"]) {
        type=ORDER_TYPE_WAIT_FOR_PAY;
        
    }else if ([statusText isEqualToString:@"已支付"]){
        type=ORDER_TYPE_WAIT_FOR_DELIVERY;
    }else if ([statusText isEqualToString:@"已发货"]){
        type=ORDER_TYPE_WAIT_FOR_RECEIPT;
    }else if ([statusText isEqualToString:@"完成"]){
        type=ORDER_TYPE_SUCCEED;
    }else if ([statusText isEqualToString:@"交易关闭"]){
        type=ORDER_TYPE_CLOSED;
    }else if ([statusText isEqualToString:@"已取消"]){
        type = ORDER_TYPE_CANCELED;
    }else if([statusText isEqualToString:@"已签收"] || [statusText isEqualToString:@"已收货"]){
        type = ORDER_TYPE_RECEIPTED;
    }
    else{
        type=ORDER_TYPE_NONE;
    }
    
    return type;
}

//搜索订单
-(void)searchOrderAction{
    NSLog(@"搜索订单");
}


#pragma mark - UITableViewDelegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return [_orderArray count];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    HROrder *order=[_orderArray objectAtIndex:section];
    
    int count=0;
    
    if (order.productList!=nil && [order.productList count]>0) {
        count=[order.productList count];
    }
    
    return count;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return HEIGHT_CELL;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return HEIGHT_HEADER_CELL;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    HROrder *order=[_orderArray objectAtIndex:section];
    
    ORDER_TYPE type=[self getOrderTypeByTextStatus:order.orderStateStr];
    
    if (type==ORDER_TYPE_NONE) {
        return HEIGHT_FOOTER_ORDERCELL_SHOW_SEPERATE;
    }else{
        return HEIGHT_FOOTER_ORDERCELL_ALL_SHOW;
    }
}


-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"orderapplycell";
    HROrderApplyCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[HROrderApplyCell alloc] init];
    }
    
    HROrder *order=[_orderArray objectAtIndex:indexPath.section];
    HROrderProductInfo *product=[order.productList objectAtIndex:indexPath.row];
    
    [cell configWithData:product];
    
    //是否显示底部间隔线
    int count=[order.productList count];
    
    if (indexPath.row==(count-1)) {
        [cell setShowBottomLine:NO];
    }else{
        [cell setShowBottomLine:YES];
    }
    
    
    return cell;
    
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    HROrder *order=[_orderArray objectAtIndex:section];
    
    HROrderApplyHeader *headerView=[[HROrderApplyHeader alloc]initWithType:APPLY_HEADER_TITLE_DESC showTopLine:YES];
    headerView.titleLabel.text=[NSString stringWithFormat:@"订单号:%@",order.orderNo];
    
    headerView.descLabel.text=order.orderStateStr;
    
    return headerView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    HROrder *order=[_orderArray objectAtIndex:section];
    ORDER_TYPE type=[self getOrderTypeByTextStatus:order.orderStateStr];
    
    HROrderApplyFooter *footerView=[[HROrderApplyFooter alloc]initWithShowBottomLine:YES AndShowSeperateView:YES andShowButtonByType:type];
    footerView.delegate=self;
    footerView.orderNo=order.orderNo;
    footerView.order=order;
    footerView.section = section;
    
    [footerView showButtonsByOrderType:type];
    
    int count=[order.productList count];
    footerView.goodsCountLabel.text=[NSString stringWithFormat:@"共%d件商品",count];
    
    if ([order.isActivity intValue]==ACTIVITY_TYPE_PRE_PAYMENT) {
        //活动
        if ([order.orderStateStr isEqualToString:@"未支付"]) {
            footerView.priceTitleLabel.text=@"支付订金:";
            footerView.goodsTotalPriceLabel.text=[NSString stringWithFormat:@"￥%@",order.depositamount];
        }else if([order.orderStateStr isEqualToString:@"已付定金"]){
            footerView.priceTitleLabel.text=@"支付尾款:";
            footerView.goodsTotalPriceLabel.text=[NSString stringWithFormat:@"￥%@",order.balanceamount];
        }else{
            footerView.priceTitleLabel.text=@"实付:";
            footerView.goodsTotalPriceLabel.text=[NSString stringWithFormat:@"￥%@",order.orderamount];
        }
    }else{
        footerView.priceTitleLabel.text=@"实付:";
        footerView.goodsTotalPriceLabel.text=[NSString stringWithFormat:@"￥%@",order.orderamount];
        
    }
    
    return footerView;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    HROrder *order=[_orderArray objectAtIndex:indexPath.section];
    ORDER_TYPE type=[self getOrderTypeByTextStatus:order.orderStateStr];
    
    //显示订单详情页面
    HRUserOrderDetailViewController *viewC = [[HRUserOrderDetailViewController alloc] initWithNibName:@"HRUserOrderDetailViewController" bundle:nil];
    viewC.orderNo=order.orderNo;
    viewC.orderType=type;
    [self.navigationController pushViewController:viewC animated:YES];
}

#pragma mark - HRProgress Delegate Methods 空数据页面委托
//随便逛逛
-(void)tapHUDButtonAction:(id)button{
    UIButton *theButton=(UIButton *)button;
    
    
    if ([theButton.titleLabel.text isEqualToString:@"重新加载"]) {
        [self loadOrderData];
    }else{
        //去逛逛
        [self.navigationController popViewControllerAnimated:YES];
    }
}


#pragma mark - Order List Footer Button Action Delegate

//申请退换货
-(void)returnsOrderProduct:(HROrder *)order{
    HROrderApplyViewController *applyViewController=[[HROrderApplyViewController alloc]initWithNibName:NIBNAME_ORDER_REFUND_AND_AFTER_SALE_APPLY bundle:nil];
    
    applyViewController.applyType=APPLY_TYPE_AFTERSALE;//售后类型
    applyViewController.order=order;
    
    [self.navigationController pushViewController:applyViewController animated:YES];
}

//评价商品
-(void)commentOrderProduct:(HROrder *)order{
    HREvaluationViewController *evaluationViewController=[[HREvaluationViewController alloc] initWithNibName:@"HREvaluationViewController" bundle:nil];
    evaluationViewController.order=order;
    
    [self.navigationController pushViewController:evaluationViewController animated:YES];
}

//再次购买
-(void)buyAgainOrderProduct:(HROrder *)order{
    
    HROrderProductInfo *productInfo=[order.productList objectAtIndex:0];
    
    NSString *productId=[productInfo.productId stringValue];
    
    HRGoodsInfoViewController *goodsInfoViewController=[[HRGoodsInfoViewController alloc]initWithNibName:NIBNAME_GOODSINFO bundle:nil];
    goodsInfoViewController.goodsId=productId;
    
    [self.navigationController pushViewController:goodsInfoViewController animated:YES];
    
}

//查看进度
-(void)viewOrderProgressByOrderId:(NSString *)orderId{
    
    HROrderProgressViewController *orderProgressViewController=[[HROrderProgressViewController alloc]initWithStyle:UITableViewStylePlain];
    
    orderProgressViewController.orderNo=orderId;//订单编号
    
    [self.navigationController pushViewController:orderProgressViewController animated:YES];
}

//确认收货
-(void)receiveProductsByOrderId:(NSString *)orderId{
    
    [self showCustomLoadingHud:kLoading inView:nil];
    
    [HRInterfaceManager receiptOrder:orderId completion:^(BOOL isSucceed, NSString *message, id data) {
       
        [self hideCustomLoadingHud];
        
        if (isSucceed) {
            //确认收货成功
            [self showSuccessHud:@"已确认收货"];
            
            //重新加载订单数据
            [HRCommonData shareCommonData].hasNewOrder=YES;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(HUD_DELAY_HIDE_SECOND * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self loadOrderData];
            });
            
        }else{
            [self showTextHUD:message];
        }
        
    }];
    
}

//取消订单
-(void)cancelOrderByOrderId:(NSString *)orderId{
    HRCancelOrderView *cancelOrderView = [[HRCancelOrderView alloc] init];
    cancelOrderView.orderNo=orderId;
    [cancelOrderView loadTable];
    
    ActionSheet* actionSheet =  [[ActionSheet alloc] initWithTitle:@"请选择取消订单的理由" delegate:self cancelButtonTitle:@"确定" viewCustom:cancelOrderView otherButtonTitles:nil];
    [actionSheet show];
    
}

//付款
-(void)paymentOrderByOrderId:(NSInteger)section{
    HROrder *order=[_orderArray objectAtIndex:section];
    NSString *subject = @"";  //订单商品标题
    for (HROrderProductInfo *product in order.productList) {
        subject = [NSString stringWithFormat:@"%@ %@",subject,product.productTitle];
    }

    NSString *amount=@"0";   //订单价格
    
    if ([order.isActivity intValue]==ACTIVITY_TYPE_PRE_PAYMENT) {
        //活动订单
        if ([order.orderStateStr isEqualToString:@"未支付"]) {
            amount=order.depositamount;//支付订金
        }else if([order.orderStateStr isEqualToString:@"已付定金"]){
            amount=order.balanceamount;//支付尾款
        }
    }else{
        amount=order.orderamount;
    }
    
    [HRPaymentManager paymentWithOrderId:order.orderNo subject:subject body:@"暂无" amount:amount completion:^(BOOL isSucceed, NSString *message) {
        if (isSucceed) {
            //更改订单状态
            [HRCommonData shareCommonData].hasNewOrder=YES;
            //push到支付成功页面
            HRPaysucceedViewController *viewC = [[HRPaysucceedViewController alloc] initWithNibName:@"HRPaysucceedViewController" bundle:nil];
            viewC.pushType = PUSH_FROM_LIST;
            [self.navigationController pushViewController:viewC animated:YES];
            
        }else{
            [self showTextHUD:message];
        }
        
    }];
}



#pragma mark - ActionSheet Delegate Methods
- (void)actionSheet:(ActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex==(-1)) {
        HRCancelOrderView *cancelOrderView=(HRCancelOrderView *)actionSheet.viewCustom;
        
        NSString *cancelReason=[cancelOrderView getCurrentSelectItem];
        NSString *orderNo=cancelOrderView.orderNo;
        
        //取消订单
        [self showCustomLoadingHud:kLoading inView:nil];
        
        [HRInterfaceManager cancelOrderById:orderNo andReason:cancelReason completion:^(BOOL isSucceed, NSString *message, id data) {
            
            [self hideCustomLoadingHud];
            
            if (isSucceed) {
                [self showSuccessHud:@"订单已取消"];
                
                //重新加载订单数据
                [HRCommonData shareCommonData].hasNewOrder=YES;
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(HUD_DELAY_HIDE_SECOND * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self loadOrderData];
                });
                
            }else{
                [self showTextHUD:message];
            }
            
        }];
        
    }
}

@end
